<template>
  <div class="withdraw">
    <div class="header">
      <div class="back" @click="handleBack">
        <div class="back-arrow"></div>
      </div>
      <div class="title">Withdraw</div>
      <div class="record" @click="goRecords">Records</div>
    </div>

    <div class="content-card">
      <div class="section-title">Currency (Account)</div>
      <div class="currency-select" @click="showCurrencyPicker = true">
        <span>INR</span>
        <van-icon name="arrow" class="arrow-right" />
      </div>
      <div class="divider"></div>

      <div class="section-title section-title-large">Payment Info</div>
      <div style="position: relative">
        <van-swipe
          class="bank-cards-container"
          @change="onSwipeChange"
          :show-indicators="false"
        >
          <van-swipe-item v-for="(bank, index) in bankAccounts" :key="index">
            <div class="bank-info">
              <div class="info-item">
                <div class="label">Bank Name</div>
                <div class="value">{{ bank.bankName }}</div>
              </div>
              <div class="info-item">
                <div class="label">Account Number</div>
                <div class="value">{{ bank.accountNumber }}</div>
              </div>
              <div class="info-item">
                <div class="label">Account Type</div>
                <div class="value">{{ bank.accountType }}</div>
              </div>
              <div class="info-item">
                <div class="label">Account Holder</div>
                <div class="value">{{ bank.accountHolder }}</div>
              </div>
              <div class="info-item">
                <div class="label">Contact Info</div>
                <div class="value">{{ bank.contactInfo }}</div>
              </div>
            </div>
          </van-swipe-item>
        </van-swipe>
        <div class="dots-wrapper">
          <div
            v-for="(bank, index) in bankAccounts"
            :key="index"
            class="dot"
            :class="{ active: currentBankIndex === index }"
          ></div>
        </div>
      </div>

      <div class="section-title" style="margin-top: 20px">Amount</div>
      <div class="amount-input">
        <div class="input-wrapper">
          <input type="number" v-model="amount" placeholder="0" />
          <div class="max-text" @click="setMaxAmount">All</div>
        </div>
      </div>
      <div class="available">Available Balance: {{ unserInfo.availableBalance }}</div>

      <div class="section-title section-title-center">Fund Password</div>
      <div class="pin-input" @click="focusInput">
        <div
          v-for="(digit, index) in pinDigits"
          :key="index"
          class="pin-box"
          :class="{ active: index == fundPassword.length }"
        >
          <span
            class="cursor"
            v-if="!isComplete && currentPinIndex === index && !digit"
            >|</span
          >
          <span
            class="pin-text"
            v-if="
              !(currentPinIndex === index && !digit) &&
              index != fundPassword.length
            "
            :style="{ marginTop: digit ? '6px' : 0 }"
            >{{ digit ? "*" : "-" }}</span
          >
        </div>
        <input
          ref="hiddenInput"
          type="tel"
          class="hidden-input"
          v-model="fundPassword"
          @input="handlePinInput"
          inputmode="numeric"
          maxlength="6"
        />
      </div>
    </div>
    <div class="submit-btn" @click="submit">Submit</div>
  </div>
</template>

<script setup name="WithdrawInr">
import { ref, computed, onMounted, onUnmounted, reactive } from "vue";
import {
  NavBar as VanNavBar,
  Icon as VanIcon,
  Swipe as VanSwipe,
  SwipeItem as VanSwipeItem,
  Field as VanField,
  Button as VanButton,
  Popup as VanPopup,
  Picker as VanPicker,
  PasswordInput as VanPasswordInput,
  NumberKeyboard as VanNumberKeyboard,
  Toast,
} from "vant";
import { UserApi } from "@/api/user.api.ts";
import { useRouter } from "vue-router";
const router = useRouter();
const showCurrencyPicker = ref(false);
const currentBankIndex = ref(0);
const amount = ref("");
const showKeyboard = ref(false);

const currencyOptions = ["INR", "USD", "EUR", "GBP"];
const bankAccounts = ref([]);
const handleBack = () => {
  router.go(-1);
};
const goRecords = () => {
  router.push("/withdrawRecord");
};
const isFormValid = computed(() => {
  return (
    amount.value > 0 &&
    fundPassword.value.length === 6 &&
    bankAccounts.value.length > 0
  );
});

const onSwipeChange = (index) => {
  currentBankIndex.value = index;
};

const onCurrencyConfirm = (value) => {
  // Handle currency selection
  showCurrencyPicker.value = false;
  Toast(`Selected: ${value}`);
};

const setMaxAmount = () => {
  amount.value = availableBalance.value;
};

const fundPassword = ref("");
const currentPinIndex = ref(0);
const hiddenInput = ref(null);

const pinDigits = computed(() => {
  return fundPassword.value
    .split("")
    .concat(Array(6 - fundPassword.value.length).fill(""));
});

const isComplete = computed(() => fundPassword.value.length === 6);

let blinkInterval = null;

const focusInput = () => {
  hiddenInput.value.focus();
  if (!isComplete.value) {
    currentPinIndex.value = Math.min(fundPassword.value.length, 5);
  }
};

const handlePinInput = (e) => {
  const value = e.target.value.replace(/\D/g, "");
  fundPassword.value = String(value.slice(0, 6));

  if (blinkInterval) clearInterval(blinkInterval);

  currentPinIndex.value = Math.min(value.length, 5);

  if (!isComplete.value) {
    blinkInterval = setInterval(() => {
      currentPinIndex.value =
        currentPinIndex.value === value.length ? -1 : value.length;
    }, 600);
  }
};

const submit = () => {
  console.log(fundPassword.value)
  if(fundPassword.value.length < 6) {
    Toast("Please enter 6 digits of the fund password");
    return;
  } 
  if(amount.value <= 0) {
    Toast("Please enter the amount to be withdrawn");
    return; 
  }
  UserApi.handleWithdraw({
    amount: amount.value,
    paymentPassword: fundPassword.value,
    bankCardId: Number(bankAccounts.value[currentBankIndex.value].id),
  }).then((res) => {
    if (res.code == 200) {
      Toast("Withdrawal request submitted"); 
    } 
  })
};
const unserInfo = ref({});
onMounted(() => {
  blinkInterval = setInterval(() => {
    currentPinIndex.value = currentPinIndex.value === 0 ? -1 : 0;
  }, 600);
  UserApi.wallet().then(res => {
    if (res.code === 200) {
      // Handle wallet data here
      unserInfo.value = res.data;
    }
  });
  UserApi.getBankCard().then((res) => {
    if (res.code == 200) {
      bankAccounts.value = res.data; // Assuming API returns an array of payment info objects
    } else {
      bankAccounts.value = [];
      // Handle error case
    }
  });
});

onUnmounted(() => {
  if (blinkInterval) clearInterval(blinkInterval);
});
</script>

<style scoped>
.withdraw {
  min-height: 100vh;
  background: #121212;
  padding-bottom: 60px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background: #1e1e1e;
  position: relative;
  box-shadow: 0 2px 4px #0003;
}
.back {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.back-arrow {
  width: 10px;
  height: 10px;
  border-top: 2px solid #e0e0e0;
  border-left: 2px solid #e0e0e0;
  transform: rotate(-45deg);
}
.title {
  font-size: 18px;
  color: #fff;
  font-weight: 500;
}
.record {
  font-size: 14px;
  color: #b0b0b0;
  cursor: pointer;
}
.content-card {
  background: #1e1e1e;
  margin: 15px;
  padding: 15px;
  border-radius: 12px;
  box-shadow: 0 1px 3px #0003;
}

.section-title {
  font-size: 14px;
  color: #b0b0b0;
  margin-bottom: 12px;
  margin-top: 10px;
}

.section-title-large {
  font-size: 16px;
  font-weight: 700;
  color: #fff;
}

.currency-select {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.arrow-right {
  width: 8px;
  height: 8px;
  border-top: 2px solid #999;
  border-right: 2px solid #999;
  transform: rotate(45deg);
}

.divider {
  height: 1px;
  background: #333333;
  margin: 0;
}
.bank-info {
  flex: 0 0 100%;
  width: 100%;
  border: 0px solid rgb(9, 17, 251);
  background-color: #3b42fc;
  padding: 15px;
  border-radius: 8px;
  -webkit-user-select: none;
  user-select: none;
  position: relative;
  box-sizing: border-box;
}

.info-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  margin-bottom: 7px;
}

.label {
  color: #000;
}

.value {
  color: #000;
}

.dots-wrapper {
  position: absolute;
  bottom: 15px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 6px;
  z-index: 1;
}

.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: all 0.3s ease;
}

.dot.active {
  width: 15px;
  border-radius: 3px;
  background: white;
}

.amount-input {
  padding: 7px 10px;
  background: #2a2a2a;
  border-radius: 4px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.amount-input input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  background: transparent;
  color: #fff;
  padding: 0;
}

.max-text {
  color: #06f;
  font-size: 14px;
  cursor: pointer;
  padding: 2px 0;
}

.available {
  font-size: 12px;
  color: #b0b0b0;
  margin-top: 8px;
}

.section-title-center {
  font-size: 18px;
  font-weight: 700;
  color: #fff;
  text-align: center;
  margin: 20px 0;
}

.pin-input {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  margin-top: 12px;
  position: relative;
}
.pin-box {
  flex: 1;
  height: 44px;
  background: #f7f7f7;
  border-radius: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: all 0.3s;
}
.pin-box.active {
  background: rgba(48, 55, 232, 0.1);
}
.cursor {
  color: #4254ef;
  animation: blink-48ad795b 1s infinite;
}
.hidden-input {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  width: 1px;
  height: 1px;
}
.pin-text {
  color: #4254ef;
}
.submit-btn {
  margin: 20px 15px;
  background: #0066ff;
  color: #fff;
  padding: 12px;
  border-radius: 10px;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 2px 8px #0066ff4d;
}
</style>
